package com.eightbears.beboy.ui.merchant.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eightbears.beboy.R;
import com.eightbears.beboy.adapter.TechnicianManagerAdapter;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.builder.PostFormBuilder;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.dialog.DefaultDialog;
import com.eightbears.beboy.entity.ShopTechnicianEntity;
import com.eightbears.beboy.entity.event.ImageBus;
import com.eightbears.beboy.entity.status.Status_Error;
import com.eightbears.beboy.ui.user.activity.UserInfoActivity;
import com.socks.library.KLog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.PARAMS_PAGE_SIZE;
import static com.eightbears.beboy.base.util.CommonAPI.URL_SHOPTECHNICIAN_LIST;
import static com.eightbears.beboy.base.util.CommonAPI.URL_UPDATESHOPTECHNICIAN;
import static com.eightbears.beboy.ui.user.activity.UserInfoActivity.PARAMS_USER_INFO;

public class TechnicianManageActivity extends BaseActivity {
    public static final String PARAMS_TECHNICIANMANAGE = "TechnicianManage";

    @BindView(R.id.rv_list)
    RecyclerView rv_list;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.ll_add)
    LinearLayout ll_add;
    @BindView(R.id.view_empty)
    LinearLayout view_empty;
    @BindView(R.id.sw)
    SwipeBackLayout sw;

    private boolean isErr = true;
    private int isEnd = 0;

    private List<ShopTechnicianEntity.DataBean.ListBean> mList;
    private TechnicianManagerAdapter mTechnicianManagerAdapter;
    private ShopTechnicianEntity.DataBean.ListBean mListBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_technician_manage);
        //订阅eventBus
        EventBus.getDefault().register(this);
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        tv_title.setText("技师管理");
        initAdapter();
    }

    private void initAdapter() {
        rv_list.setLayoutManager(new LinearLayoutManager(mContext));
        mTechnicianManagerAdapter = new TechnicianManagerAdapter(mContext);
        rv_list.setAdapter(mTechnicianManagerAdapter);

    }

    @Override
    protected void initData() {
        getData();
    }

    @Override
    protected void initEvent() {
        mTechnicianManagerAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                mListBean = (ShopTechnicianEntity.DataBean.ListBean) adapter.getData().get(position);
                switch (view.getId()) {
                    case R.id.tv_edit:
                        startLocalActivity((Activity) mContext, AddTechnicianActivity.class, PARAMS_TECHNICIANMANAGE, mListBean);
                        break;
                    case R.id.tv_del:
                        deleteItem(position);
                        break;
                    case R.id.iv_cover:
                        startLocalActivity(TechnicianManageActivity.this,
                                UserInfoActivity.class, PARAMS_USER_INFO, mListBean.getUser_id());
                        break;
                }
            }
        });

        sw.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });
    }


    @OnClick(R.id.ll_back)
    void back() {
        finish();
    }

    @OnClick(R.id.ll_add)
    void add() {
        startLocalActivity((Activity) mContext, AddTechnicianActivity.class, PARAMS_TECHNICIANMANAGE, null);
    }

    /**
     * 获取技师列表
     */
    //TODO
    public void getData() {
        int page = 1;
        OkHttpUtils.get().url(URL_SHOPTECHNICIAN_LIST + SPUtil.getUser().getData().getShops().get(0).getShop_id() + "/girls")
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("page", String.valueOf(page))
                .addParams("size", PARAMS_PAGE_SIZE)
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                KLog.e(response);
                ShopTechnicianEntity shopTechnicianEntity = GsonUtil.fromJson(response, ShopTechnicianEntity.class);
                mList = shopTechnicianEntity.getData().getList();
                if (CONNECTION_STATUS_SUCCESS.equals(String.valueOf(shopTechnicianEntity.getStatus_code()))) {
                    isEnd = shopTechnicianEntity.getData().getIs_end();
                    mTechnicianManagerAdapter.setNewData(mList);
                    rv_list.setAdapter(mTechnicianManagerAdapter);
                    if (shopTechnicianEntity.getData().getList().size() == 0) {
                        view_empty.setVisibility(View.VISIBLE);
                        rv_list.setVisibility(View.GONE);
                    } else {
                        view_empty.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                KLog.e(e.getMessage());
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError((Activity) mContext, status_error);
            }
        });
    }


    /**
     * 删除item
     */
    public void deleteItem(final int position) {
        //弹出对话框
        DefaultDialog.Builder defaultDialog = new DefaultDialog.Builder(mContext);
        defaultDialog.setTitle(getString(R.string.alert_text));
        defaultDialog.setMessage("是否要删除这位技师？");

        defaultDialog.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                delData();
                //删除数据库
                mTechnicianManagerAdapter.remove(position);
                mTechnicianManagerAdapter.notifyDataSetChanged();
                dialog.dismiss();
            }
        });
        defaultDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        defaultDialog.create().show();
    }

    /**
     * 删除数据
     */
    public void delData() {
        PostFormBuilder builder = OkHttpUtils.post();//创建请求构建器
        builder.url(URL_UPDATESHOPTECHNICIAN + mListBean.getId());
        builder.addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken());
        builder.addParams("status", "0");
        builder.build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                ShowToast.showShortToast("删除成功");

            }

            @Override
            public void onError(Call call, Exception e) {
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError((Activity) mContext, status_error);
                ShowToast.showShortToast("删除成功");
            }
        });
    }

    /**
     * 刷新列表
     *
     * @param
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(ImageBus event) {
        if (event.getMsg().equals("refresh_addTechnician")) {
            getData();//刷新数据
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
